package cn.com.wdjedu.androidapp.wjeduandroid;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.Constanct;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.view.DeletableEditText;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.view.MyGifView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by CCY on 2017/3/29.
 */

public class RegistActivity extends Activity {
    @BindView(R.id.tv_reg_phone)
    DeletableEditText tvRegPhone;
    @BindView(R.id.tv_reg_psw_check)
    DeletableEditText tvRegPswCheck;
    @BindView(R.id.tv_reg_sms_code)
    DeletableEditText tvRegSmsCode;
    @BindView(R.id.bt_reg_sms_code)
    Button btRegSmsCode;
    @BindView(R.id.bt_regist)
    Button btRegist;
    @BindView(R.id.tv_reg_psw)
    DeletableEditText tvRegPsw;
    @BindView(R.id.regist_form)
    ScrollView registForm;
    @BindView(R.id.progressBar2)
    ProgressBar progressBar2;
    @BindView(R.id.tv_regist_title)
    TextView tvRegistTitle;
    @BindView(R.id.sheep_gif)
    MyGifView sheepGif;
    @BindView(R.id.textViewLoading)
    TextView textViewLoading;

    private UserRegistTask mAuthTask = null;
    //get方法返回的短信验证码json数据
    private String SmsCodeJSON;
    //更新UI线程
    private Runnable updateThread;
    private Runnable updateThread_failed;
    //请求超时时更新线程
    private Runnable updateThread_Overtime;
    //类型：忘记密码或注册
    private String type;

    //计时器
    private CountDownTimer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        ButterKnife.bind(this);

        initView();
    }

    public void initView() {
        type = getIntent().getStringExtra("type");
        if (type.equals("register")) {
            btRegist.setText("注册");
            tvRegistTitle.setText("账号注册");
        } else {
            btRegist.setText("保存修改");
            tvRegistTitle.setText("密码重置");
        }
        btRegSmsCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attemptGetSmsCode();
            }
        });
        btRegist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attemptRegist();
            }
        });

        registForm.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (mAuthTask != null && mAuthTask.getStatus() == AsyncTask.Status.RUNNING) {
                    showProgress(false);
                    mAuthTask.cancel(true); // 如果Task还在运行，则先取消它
                    mAuthTask = null;
                    timer.cancel();
                }
                return true;
            }
        });

        //请求超时时更新线程
        updateThread_Overtime = new Runnable() {
            @Override
            public void run() {
                try {
                    //更新UI
                    Toast.makeText(getApplicationContext(), "请求超时,请检查网络", Toast.LENGTH_SHORT).show();
                    if (mAuthTask != null && mAuthTask.getStatus() == AsyncTask.Status.RUNNING) {
                        showProgress(false);
                        mAuthTask.cancel(true); // 如果Task还在运行，则先取消它
                        mAuthTask = null;
                        timer.cancel();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }


    private void attemptGetSmsCode() {
        tvRegPhone.setError(null);
        String phone = tvRegPhone.getText().toString();

        boolean cancel = false;
        View focusView = null;

        if (!isPhoneValid(phone)) {
            tvRegPhone.setError(getString(R.string.error_invalid_email));
            focusView = tvRegPhone;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // 执行短信验证码get请求
            UserSmsCodeTask(phone, type);
            btRegSmsCode.setEnabled(false);
            btRegSmsCode.setText("60");
           new CountDownTimer(60000, 1000) {
                public void onTick(long millisUntilFinished) {
                    btRegSmsCode.setText("" + millisUntilFinished / 1000);
                }
                public void onFinish() {
                    btRegSmsCode.setText("获取验证码");
                    btRegSmsCode.setEnabled(true);
                }
            }.start();
        }
    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptRegist() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        tvRegPhone.setError(null);
        tvRegPsw.setError(null);
        tvRegPswCheck.setError(null);
        // Store values at the time of the login attempt.
        String phone = tvRegPhone.getText().toString();
        String password = tvRegPsw.getText().toString();
        String password_check = tvRegPswCheck.getText().toString();
        String code = tvRegSmsCode.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            tvRegPsw.setError(getString(R.string.error_invalid_password));
            focusView = tvRegPsw;
            cancel = true;
        }

        // Check for a valid phone address.
        if (TextUtils.isEmpty(phone)) {
            tvRegPhone.setError(getString(R.string.error_field_required));
            focusView = tvRegPhone;
            cancel = true;
        } else if (!isPhoneValid(phone)) {
            tvRegPhone.setError(getString(R.string.error_invalid_email));
            focusView = tvRegPhone;
            cancel = true;
        }

        //确认密码
        if (!password_check.equals(password)) {
            tvRegPswCheck.setError(getString(R.string.error_password_check));
            focusView = tvRegPswCheck;
            cancel = true;
        }

        //确认验证码格式
        if (isSmsCodeValid(code)) {
            tvRegSmsCode.setError(getString(R.string.error_smscode_check));
            focusView = tvRegSmsCode;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserRegistTask(phone, password, code);
            mAuthTask.execute((Void) null);

            //请求超时时
         timer =  new CountDownTimer(10000, 1000) {
                public void onTick(long millisUntilFinished) {
                }
                public void onFinish() {
                    RegistActivity.this.runOnUiThread(updateThread_Overtime);
                    if (mAuthTask != null && mAuthTask.getStatus() == AsyncTask.Status.RUNNING) {
                        showProgress(false);
                        mAuthTask.cancel(true); // 如果Task还在运行，则先取消它
                        mAuthTask = null;
                        timer.cancel();
                    }
                }
            };
            timer.start();
        }
    }

    private boolean isPhoneValid(String phone) {
        //TODO: Replace this with your own logic
         /*
          移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
          联通：130、131、132、152、155、156、185、186
          电信：133、153、180、189、（1349卫通）
          总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
         */
        String num = "[1][358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(phone)) {
            return false;
        } else {
            //matches():字符串是否在给定的正则表达式匹配
            return phone.matches(num);
        }
        // return phone.contains("@");
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() >= 6;
    }

    private boolean isSmsCodeValid(String smscode) {
        //TODO: Replace this with your own logic
        String num = "\\d{7}";  //验证码为6位数
        if (TextUtils.isEmpty(smscode)) {
            return false;
        } else {
            //matches():字符串是否在给定的正则表达式匹配
            return smscode.matches(num);
        }
    }


    /**
     * Shows the progress UI and hides the regist form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            registForm.setAlpha(show ? (float) 0.3 : (float) 1 );
            registForm.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    registForm.setAlpha(show ? (float) 0.3 : (float) 1 );
                }
            });

            progressBar2.setVisibility(show ? View.VISIBLE : View.GONE);
            progressBar2.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    progressBar2.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });

            sheepGif.setVisibility(show ? View.VISIBLE : View.GONE);
            sheepGif.setMovieResource(R.raw.sheep);

            textViewLoading.setVisibility(show ? View.VISIBLE : View.GONE);
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            progressBar2.setVisibility(show ? View.VISIBLE : View.GONE);
            sheepGif.setVisibility(show ? View.VISIBLE : View.GONE);
            textViewLoading.setVisibility(show ? View.VISIBLE : View.GONE);

            registForm.setAlpha(show ? (float) 0.3 : (float) 1 );
        }
    }

    private boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    /**
     * 发送短信验证码的get请求
     */
    public void UserSmsCodeTask(String phone, String type) {
        final OkHttpClient okHttpClient = new OkHttpClient()
                .newBuilder()
                .build();
        final Request request = new Request.Builder()
                .url(Constanct.DOMAIN+"common/sms?phone=" + phone + "&type=" + type)
                .header("User-Agent", "OkHttp Example")
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        RegistActivity.this.runOnUiThread(updateThread_failed);
                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        SmsCodeJSON = response.body().string();
//                        Log.d("Raj","response====="+response.body().string());
                        RegistActivity.this.runOnUiThread(updateThread);
                        response.body().close();
                    }
                });
            }
        }).start();

        //请求失败时更新线程
        updateThread_failed = new Runnable() {
            @Override
            public void run() {
                try {
                    //更新UI
                    Toast.makeText(getApplicationContext(), "请求失败,请检查网络", Toast.LENGTH_LONG).show();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        };

        //根据返回的信息更新UI
        updateThread = new Runnable() {
            @Override
            public void run() {
                try {
                    //更新UI
                    JSONObject jsonObject = new JSONObject(SmsCodeJSON);
                    JSONObject jsonObject2 = new JSONObject(jsonObject.get("resultData").toString());
                    switch (Integer.parseInt(jsonObject2.get("code").toString())) {
                        case 200:
                            Log.d("Raj", "注册信息=====" + jsonObject2.get("message").toString());
                            break;
                        case 201:
                            Log.d("Raj", "注册信息=====" + jsonObject2.get("message").toString());
                            tvRegSmsCode.setError("发送短信失败");
                            break;
                        case 202:
                            Log.d("Raj", "注册信息=====" + jsonObject2.get("message").toString());
                            tvRegSmsCode.setError("限制时间内重复发送");
                            break;
                        case 1000:
                            Log.d("Raj", "注册信息=====" + jsonObject2.get("message").toString());
                            tvRegPsw.setError("参数类型错误");
                            break;
                        case 1001:
                            Log.d("Raj", "注册信息=====" + jsonObject2.get("message").toString());
                            tvRegPhone.setError("手机已经注册");
                            break;
                        case 1002:
                            Log.d("Raj", "注册信息=====" + jsonObject2.get("message").toString());
                            tvRegPhone.setError("手机尚未注册");
                            break;
                        case 1003:
                            Log.d("Raj", "注册信息=====" + jsonObject2.get("message").toString());
                            tvRegSmsCode.setError("手机验证码错误");
                            tvRegSmsCode.requestFocus();
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        };
    }


    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserRegistTask extends AsyncTask<Void, Void, String> {

        private final String mPhone;
        private final String mPassword;
        private final String mSmsCode;

        UserRegistTask(String phone, String password, String smscode) {
            mPhone = phone;
            mPassword = password;
            mSmsCode = smscode;
        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            String result = null;
            OkHttpClient client = new OkHttpClient();
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("phone", mPhone);
            builder.add("password", mPassword);
            builder.add("code", mSmsCode);

            RequestBody body = builder.build();
            Request request = new Request.Builder()
                    .url(Constanct.DOMAIN+"common/" + type)
                    .post(body)
                    .build();
            Response response = null;
            try {
                response = client.newCall(request).execute();
                result = response.body().string();

            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (!isNetWorkConnected(getApplicationContext()))
            {
                Toast.makeText(getApplicationContext(), "请求失败,请检查网络", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected void onPostExecute(String s) {
            if (mAuthTask != null && mAuthTask.getStatus() == AsyncTask.Status.RUNNING) {
                showProgress(false);
                mAuthTask.cancel(true); // 如果Task还在运行，则先取消它
                mAuthTask = null;
                timer.cancel();
            }
            // Toast.makeText(getApplicationContext(),"test",Toast.LENGTH_LONG).show();
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONObject jsonObject2 = new JSONObject(jsonObject.get("resultData").toString());

                switch (Integer.parseInt(jsonObject2.get("code").toString())) {
                    case 200:
                        Toast.makeText(getApplicationContext(), "" + jsonObject2.get("message"), Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(getApplication(), Login.class));
                        finish();
                        break;
                    case 201:
                        mAuthTask = null;
                        showProgress(false);
                        tvRegPhone.setError(getString(R.string.error_network));
                        break;
                    case 1000:
                        mAuthTask = null;
                        showProgress(false);
                        tvRegPhone.setError(getString(R.string.error_parameter));
                        break;
                    case 1001:
                        mAuthTask = null;
                        showProgress(false);
                        if (type.equals("register")) {
                            tvRegPhone.setError(getString(R.string.error_phone_already));
                        } else {
                            tvRegSmsCode.setError(getString(R.string.error_invalid_code));
                        }
                        break;
                    case 1002:
                        mAuthTask = null;
                        showProgress(false);
                        tvRegSmsCode.setError(getString(R.string.error_invalid_code));
                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            super.onPostExecute(s);
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);

        }
    }
}
